//app.js
var server = require('utils/server.js');
var QQMapWX = require('utils/libs/qqmap-wx-jssdk.min.js');

App({
  onLaunch: function() {
    var that = this;
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    // 获取用户信息
    // 实例化API核心类
    var qqmapsdk = new QQMapWX({
      key: '74OBZ-F2RCP-ITVDN-LF3HC-HVKWK-XQFQY'
    });
    that.globalData.qqmapsdk = qqmapsdk;

  },
  /**
   * 获取用户当前的经纬度
   */
  getLocation: function() {
    return new Promise(function(resolve, reject) {
      var app = getApp();
      var that = this;
      //获取用户当前的经纬度
      wx.getLocation({
        type: 'wgs84',
        altitude: 'true',
        success: function(res) {
          var latitude = res.latitude
          var longitude = res.longitude
          app.globalData.longitude = longitude;
          app.globalData.latitude = latitude;
          console.log(res)
          resolve(res);
        },
        fail: function(res) {
          // typeof cb == "function" && cb();
        }
      })
    })

  },

  /**
   * 获取地区信息
   */
  getDistrict: function() {
    return new Promise(function(resolve, reject) {
      var that = this;
      //获取用户当前的经纬度
      var app = getApp();
      wx.getLocation({
        type: 'wgs84',
        altitude: 'true',
        success: function(res) {
          var latitude = res.latitude
          var longitude = res.longitude
          // app.globalData.longitude = longitude;
          // app.globalData.latitude = latitude;
          var qqsdk = app.globalData.qqmapsdk;
          qqsdk.reverseGeocoder({
            location: {
              latitude: latitude,
              longitude: longitude
            },
            //get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
            success: function(res) { //成功后的回调
              if (res.result) {

                resolve(res.result.address_component.district);
              }
            },
            fail: function(error) {
             
            },
            complete: function(res) {

            }
          })
        },
        fail: function(res) {
          typeof cb == "function" && cb();
        }
      })
    })
  },
  wxlogin: function(cb) {
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        var app = getApp();
        if (res.code) {
          var param = "getWxOpenid?code=" + res.code;
          server.postJSON(param, function(res1) {
            if (res1.data.success == true) {

              app.globalData.openid = res1.data.data.openid;
              app.globalData.unionid = res1.data.data.unionid;
              app.globalData.sessionkey = res1.data.data.sessionkey;
              typeof cb == "function" && cb();
            } else {
               
              typeof cb == "function" && cb();
            }
          })
        } else {
          console.log("获取code失败");
        }

      }
    })
  },
  /**
   * 判断用户是否已存在
   * */
  openidsaved: function(cb) {
    var app = getApp();
    var that = this;
    var lng = app.globalData.longitude;
    var lat = app.globalData.latitude;
    console.log(app.globalData.openid)
    var param = "openidsaved?lng=" + lng + "&lat=" + lat + "&openid=" + app.globalData.openid + "&unionid=" + app.globalData.unionid;

    server.postJSON(param, function(res) {
      if (res.data.data!=null){
        app.globalData.userInfo = res.data.data;
        console.log(app.globalData.userInfo);
      }
      typeof cb == "function" && cb();
    })
  },
  /**
   * 获取用户信息
   * 
   */

  getUserInfo: function(cb) {
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              // this.globalData.userInfo = res.userInfo
              if (res.userInfo) {
                var app = getApp();
                var parameter = {
                  openid: app.globalData.openid,
                  sessionkey: app.globalData.sessionkey,
                  encryptedData: res.encryptedData,
                  iv: res.iv,
                  unionid: app.globalData.unionid,
                  lat: app.globalData.latitude,
                  lng: app.globalData.longitude,
                }
                server.getJSON("userLogin", parameter, function(res) {
                  if (res.data.success == true) {
                    app.globalData.userInfo = res.data.data;

                  } else {
                    console.log(res.data.msg)
                  }
                  typeof cb == "function" && cb()
                });
              }
              typeof cb == "function" && cb();
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },

  /**
   * 全局变量
   */
  globalData: {
    isrefresh:'0',
    //api:'http://7jh9it.natappfree.cc/api',
     api: 'https://my.yhup.top/api',
    selectdisctrict:'',
    qqmapsdk: '',
    "sessionkey": "",
    openid: "",
    unionid: '',
    longitude: "",
    latitude: "",
    'encryptedData': null,
    'iv': null,
    userInfo: {
      userid:''
    },
    searchText:'',
    //搜索历史
    searchhistory: []
  }
})